#include "tcp_client.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdio.h>
#include "socket_tool.h"
#include <string.h>
#include <stdlib.h>
#include <sys/select.h>

void start_client()
{
    puts("启动客户端");

    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    struct sockaddr_in server_ipv4;
    server_ipv4.sin_family = AF_INET;
    server_ipv4.sin_port = htons(12345);
    inet_pton(AF_INET, "127.0.0.1", &server_ipv4.sin_addr.s_addr);

    connect(sockfd, (struct sockaddr*) &server_ipv4, sizeof(server_ipv4));

    char *server = sockaddr_to_string(&server_ipv4);
    printf("连接成功,server=%s\n", server);
    free(server);

    char send_buf[256];
    memset(send_buf, 0, sizeof(send_buf));

    int stdin_fd = fileno(stdin);
    int max = sockfd > stdin_fd ? sockfd : stdin_fd;
    int maxfd1 = max + 1;
    fd_set fdset;
    FD_ZERO(&fdset);
    FD_SET(stdin_fd, &fdset);
    FD_SET(sockfd, &fdset);
    while (true)
    {
        fd_set wait_set = fdset;
        // 阻塞在select上
        int ready_number = select(maxfd1, &wait_set, NULL, NULL, NULL);
        if (ready_number < 0) {
            puts("select返回错误");
            break;
        }

        if (FD_ISSET(stdin_fd, &wait_set)) {
            // 发送消息，fgets会读取换行符，并自动添加\0
            fgets(send_buf, sizeof(send_buf), stdin);
            // 加1是为了传输\0
            write(sockfd, send_buf, strlen(send_buf) + 1);

            if (strcmp("bye\n", send_buf) == 0) {
                puts("关闭连接");
                // 显示调用close关闭套接字
                close(sockfd);
                exit(0);
            }
        }

        if (FD_ISSET(sockfd, &wait_set)) {
            // 接收消息
            String *msg = read_tcp_line(sockfd);
            if (msg == NULL) {
                puts("服务器发送FIN关闭连接");
                break;
            }
            printf("接收到服务器的消息：%s\n", msg->start);
            if (strcmp("bye", msg->start) == 0) {
                Destroy_String(msg);
                puts("服务器发送bye关闭连接");
                return;
            }
            Destroy_String(msg);
        }

    }
    

}